package api

import (
	"bytes"
	"encoding/binary"
	"encoding/json"
	"errors"
	"fmt"
	"github.com/aceld/zinx/utils"
	"github.com/aceld/zinx/ziface"
	dbutil "github.com/aceld/zinx/zinx_modbus_tcp/dao"
	"github.com/aceld/zinx/znet"
	//"github.com/aceld/zinx/log"
	log "github.com/cihub/seelog"
	_ "github.com/go-sql-driver/mysql"
	"time"
)



//注册设备
type RegisterApi struct {
	znet.BaseRouter
}

//门磁电池数据处理
type BatteryVoltageDoorMagnetismApi struct{
	znet.BaseRouter
}

//门磁数据处理
type DoorMagnetismApi struct {
	znet.BaseRouter
}

//水浸电池数据处理
type BatteryVoltageWaterImmersion struct{
	znet.BaseRouter
}

//水浸数据处理
type WaterImmersion struct{
	znet.BaseRouter
}

//烟感电池数据处理
type BatteryVoltageSmokeSensation struct{
	znet.BaseRouter
}

//烟感数据处理
type SmokeSensation struct{
	znet.BaseRouter
}

//温度传感器电池电压数据处理
type BatteryVoltageTemperature struct {
	znet.BaseRouter
}


//温度数据处理
type Temperature struct{
	znet.BaseRouter
}


//水位电池电压数据处理
type BatteryVoltageWaterLevel struct {
	znet.BaseRouter
}

//水位数据处理
type WaterLevel struct{
	znet.BaseRouter
}


//水位电池电压数据处理
type BatteryVoltageTempAndHum struct {
	znet.BaseRouter
}

//温湿度数据处理
type TempAndHum struct{

	znet.BaseRouter
}





type Operator struct {
	OperatorType   int			`json:"operator"`
	Rssi    int                 `json:"rssi"`
}

type KeyValue struct {
	Key string 	`json:"key"`
	Unit string  `json:"unit"`
	Value string `json:"value"`
}



type Event struct {
	Level     int32  `protobuf:"varint,1,opt,name=level,proto3" json:"level,omitempty"`
	Type      int32  `protobuf:"varint,2,opt,name=type,proto3" json:"type,omitempty"`
	Sender    string `protobuf:"bytes,3,opt,name=sender,proto3" json:"sender,omitempty"`
	Content   string `protobuf:"bytes,4,opt,name=content,proto3" json:"content,omitempty"`
	CreatedAt string `protobuf:"bytes,5,opt,name=createdAt,proto3" json:"createdAt,omitempty"`
	KeyValue  string `protobuf:"bytes,6,opt,name=keyValue,proto3" json:"keyValue,omitempty"`
}

type MeterStatus struct{
	Status uint8	`json:"status"`
	SiteId uint32	`json:"siteid"`
	Lasttime string  `json:"lasttime"`
	Protocol	string	`json:"protocol"`
}

type MeterPointInfo struct{

	Name string	`json:"name"`
	Unit string	`json:"unit"`
	TabName string `json:"tabname"`
	Radio float32  `json:"radio"`
	CtFlag int8		`json:"ctflag"`
	PtFlag int8 	`json:"ptflag"`
}


type SiteParams struct {

	//信工温度数量
	NumTemp        uint16 		`json:"numTemp"`
	//信工水浸数量
	NumWaterImmersion uint16	`json:"numWaterImmersion"`
	//信工水位
	NumWaterLevel uint16		`json:"numWaterLevel"`
	//信工温湿度
	NumTempAndHum uint16		`json:"numTempAndHum"`
	//信工门磁
	NumDoorMagnetism uint16		`json:"numDoorMagnetism"`
	//信工烟感
	NumSmokeSensation uint16	`json:"numSmokeSensation"`

}



func getBit(data uint16,index uint16) (uint16,error) {

	if index>15{
		return 0,errors.New("长度超出")
	}
	iss := data>>index
	res := iss & 1

	return res,nil

}



func checkMessageFormat(request ziface.IRequest) (error,*SiteParams){

	siteParams := &SiteParams{}
	registerBuff := request.GetData()
	msgID :=request.GetMsgID()
	fmt.Printf(string(msgID))
	//dataBuff := bytes.NewReader(registerBuff)
	log.Debugf("%2X ",registerBuff)
	//conn := request.GetConnection()

	byteUuid := registerBuff[0:7]

	var site_sid string
	site_sid= fmt.Sprintf( "%2X", byteUuid)
	fmt.Println(site_sid)

	conn :=  request.GetConnection()
	iSiteSid,err := conn.GetProperty("siteSid")
	if err !=nil{
		log.Infof("conn.GetProperty fail:%v",err)
		return err,siteParams
	}

	siteSid,ok := iSiteSid.(string)

	if !ok{
		log.Infof("IsiteSid fail")
		return err,siteParams
	}

	if site_sid == siteSid{

		fmt.Printf(string(msgID))

		mbap := registerBuff[7:14]


		mbapBuff := bytes.NewReader(mbap)

		var transactionId uint16
		var protocolIdentifier uint16
		var length	uint16
		var slaveId uint8


		if err := binary.Read(mbapBuff, binary.BigEndian, &transactionId); err != nil {
			log.Debug("读取transactionId失败")
			return err,siteParams
		}

		if err := binary.Read(mbapBuff, binary.BigEndian, &protocolIdentifier); err != nil {
			log.Debug("读取protocolIdentifier失败")
			return err,siteParams
		}

		if err := binary.Read(mbapBuff, binary.BigEndian, &length); err != nil {
			log.Debug("读取length失败")
			return err,siteParams
		}

		if err := binary.Read(mbapBuff, binary.BigEndian, &slaveId); err != nil {
			log.Debug("读取slaveId失败")
			return err,siteParams
		}

		if transactionId != uint16(msgID){

			log.Debug("transactionId != uint16(msgID)")
			return errors.New("transactionId != uint16(msgID)"),siteParams
		}

		if protocolIdentifier != 0{
			log.Debug("protocolIdentifier != 0")
			return errors.New("protocolIdentifier != 0"),siteParams
		}

		if length != uint16(len(registerBuff)-13){
			log.Debug("length != uint16(len(registerBuff)-13)")
			return errors.New("length != uint16(len(registerBuff)-13)"),siteParams
		}



		data := registerBuff[14:(14+length-1)]
		dataBuff := bytes.NewReader(data)

		var functionCode uint8
		var datalen uint8

		if err := binary.Read(dataBuff, binary.BigEndian, &functionCode); err != nil {
			log.Debug("读取functionCode失败")
			return err,siteParams
		}

		if err := binary.Read(dataBuff, binary.BigEndian, &datalen); err != nil {
			log.Debug("读取functionCode失败")
			return err,siteParams
		}

		strReply,err := dbutil.HashGet(utils.GATEWAY_SITE_XINGONG,site_sid)
		if err !=nil{
			log.Infof("设备查询失败或未同步到redis:%v",site_sid)
			return err,siteParams
		}

		err =json.Unmarshal([]byte(strReply), &siteParams)
		if err!=nil{
			log.Infof("json反序列化失败:%v",strReply)
			return err,siteParams
		}

		return nil,siteParams
	}else{
		return errors.New("site_sid == siteSid"),siteParams
	}

}



func (*RegisterApi) Handle (request ziface.IRequest)  {


	 registerBuff := request.GetData()
	 //msgID := request.GetMsgID()
	 //dataBuff := bytes.NewReader(registerBuff)
	 log.Debug("%2X",registerBuff)

	 if len(registerBuff) < 7{
		 return
	 }

	 if registerBuff[0] == 0xA8 && registerBuff[1] == 0x01{

	 	byteUuid := registerBuff[0:7]

	 	var site_sid string
		 site_sid= fmt.Sprintf( "%2X", byteUuid)

	 	//检查uuid在redis是否存在，
		 reply,err:=dbutil.Hashhexists(utils.GATEWAY_SITE_XINGONG,site_sid)
		 if err !=nil{
			 log.Infof("查找站点出错:",site_sid)
			 return
		 }
		 if reply == 0{
			 log.Infof("查找不到站点:",site_sid)
			 return
		 }

	 	//获取链接
	 	conn := request.GetConnection()


	 	iAskType,err := conn.GetProperty("askType")
		conn.SetProperty("siteSid",site_sid)

	 	if err !=nil{
			return
		}

		askType, ok := iAskType.(int)
		if !ok{
			return
		}

		 strReply,err := dbutil.HashGet(utils.GATEWAY_SITE_XINGONG,site_sid)
		 if err !=nil{
			 log.Infof("设备查询失败或未同步到redis:%v",site_sid)
			 return
		 }
		 sitePrarms := &SiteParams{}
		 err =json.Unmarshal([]byte(strReply), &sitePrarms)
		 if err!=nil{
			 log.Infof("json反序列化失败:%v",strReply)
			 return
		 }

		 //更新站点时间
		 dbutil.UpdateSiteTime(site_sid)

		if askType == 0{
			conn.SetProperty("lastTime",time.Now())
			data, _ := utils.ReadHoldingRegisters(1,2001,sitePrarms.NumTemp, uint32(askType))
			fmt.Printf( "send: %2X ", data)
			conn.SetProperty("askType",askType+1)
			conn.SetTimeOut(time.Second*10)
			conn.SendMsg(1,data)
		}
		//else{
		//	timeLast, _ :=conn.GetProperty("lastTime")
		//	subM := time.Now().Sub(timeLast.(time.Time))
		//	if subM.Seconds() >30{
		//		//30s未更新
		//		conn.Stop()
		//	}
		//}

	 }else{
		 return
	 }

}



func (*BatteryVoltageTemperature) Handle (request ziface.IRequest){

	registerBuff := request.GetData()
	msgID :=request.GetMsgID()
	fmt.Printf(string(msgID))
	//dataBuff := bytes.NewReader(registerBuff)
	log.Debugf("%2X ",registerBuff)
	//conn := request.GetConnection()

	byteUuid := registerBuff[0:7]

	var site_sid string
	site_sid= fmt.Sprintf( "%2X", byteUuid)
	fmt.Println(site_sid)

	conn :=  request.GetConnection()
	iSiteSid,err := conn.GetProperty("siteSid")
	if err !=nil{
		log.Infof("conn.GetProperty fail:%v",err)
		return
	}

	siteSid,ok := iSiteSid.(string)

	if !ok{
		log.Infof("IsiteSid fail")
		return
	}

	if site_sid == siteSid{

		mbap := registerBuff[7:14]


		mbapBuff := bytes.NewReader(mbap)

		var transactionId uint16
		var protocolIdentifier uint16
		var length	uint16
		var slaveId uint8


		if err := binary.Read(mbapBuff, binary.BigEndian, &transactionId); err != nil {
			log.Debug("读取transactionId失败")
			return
		}

		if err := binary.Read(mbapBuff, binary.BigEndian, &protocolIdentifier); err != nil {
			log.Debug("读取protocolIdentifier失败")
			return
		}

		if err := binary.Read(mbapBuff, binary.BigEndian, &length); err != nil {
			log.Debug("读取length失败")
			return
		}

		if err := binary.Read(mbapBuff, binary.BigEndian, &slaveId); err != nil {
			log.Debug("读取slaveId失败")
			return
		}

		if transactionId != uint16(msgID){

			return
		}

		if protocolIdentifier != 0{
			return
		}

		if length != uint16(len(registerBuff)-13){
			return
		}



		data := registerBuff[14:(14+length-1)]
		dataBuff := bytes.NewReader(data)

		var functionCode uint8
		var datalen uint8

		if err := binary.Read(dataBuff, binary.BigEndian, &functionCode); err != nil {
			log.Debug("读取functionCode失败")
			return
		}

		if err := binary.Read(dataBuff, binary.BigEndian, &datalen); err != nil {
			log.Debug("读取functionCode失败")
			return
		}

		strReply,err := dbutil.HashGet(utils.GATEWAY_SITE_XINGONG,site_sid)
		if err !=nil{
			log.Infof("设备查询失败或未同步到redis:%v",site_sid)
			return
		}
		siteParams := &SiteParams{}
		err =json.Unmarshal([]byte(strReply), &siteParams)
		if err!=nil{
			log.Infof("json反序列化失败:%v",strReply)
			return
		}

		if siteParams.NumTemp <=120{

			if siteParams.NumTemp == uint16(datalen/2){


				for i:=uint16(0);i< siteParams.NumTemp ;i++{

					var battryVoltage uint16
					if err := binary.Read(dataBuff, binary.BigEndian, &battryVoltage); err != nil {
						log.Debug("读取slaveId失败")
						return
					}

					if battryVoltage !=0{

						fbattryVoltage := float32(battryVoltage)*10.0 //

						uuid := fmt.Sprintf("%sC3%04d",site_sid,i+1)
						reply,err := dbutil.HashGet(utils.DEVICES_STATUS_HASH,uuid)
						if err !=nil{
							log.Infof("设备查询失败或未同步到redis:%v",uuid)
							continue
						}
						meterLastStatus := MeterStatus{}
						err =json.Unmarshal([]byte(reply), &meterLastStatus)
						if err!=nil{
							log.Infof("json反序列化失败:%v",reply)
							continue
						}
						err = dbutil.StringSet(utils.DEVICES_VALUE_STRING+":"+uuid+":"+"battery",fbattryVoltage)
						if err != nil{
							log.Errorf("存储数据失败：%v:%v-%v",uuid,"battery",fbattryVoltage)
						}
					}

				}
			}


			//下一次询问温度
			if msgID == 1{
				askType := int(msgID)
				data, _ := utils.ReadHoldingRegisters(1,1,siteParams.NumTemp, uint32(askType))
				fmt.Printf( "send: %2X ", data)
				conn.SetProperty("askType",askType+1)
				conn.SetTimeOut(time.Second*10)
				conn.SendMsg(uint8(askType+1),data)
			}


		}else{



		}

	}

}

func (*Temperature) Handle (request ziface.IRequest){

	registerBuff := request.GetData()
	msgID :=request.GetMsgID()
	fmt.Printf(string(msgID))
	//dataBuff := bytes.NewReader(registerBuff)
	log.Debugf("%2X ",registerBuff)
	//conn := request.GetConnection()

	byteUuid := registerBuff[0:7]

	var site_sid string
	site_sid= fmt.Sprintf( "%2X", byteUuid)
	fmt.Println(site_sid)

	conn :=  request.GetConnection()
	iSiteSid,err := conn.GetProperty("siteSid")
	if err !=nil{
		log.Infof("conn.GetProperty fail:%v",err)
		return
	}

	siteSid,ok := iSiteSid.(string)

	if !ok{
		log.Infof("IsiteSid fail")
		return
	}

	if site_sid == siteSid{

		mbap := registerBuff[7:14]


		mbapBuff := bytes.NewReader(mbap)

		var transactionId uint16
		var protocolIdentifier uint16
		var length	uint16
		var slaveId uint8


		if err := binary.Read(mbapBuff, binary.BigEndian, &transactionId); err != nil {
			log.Debug("读取transactionId失败")
			return
		}

		if err := binary.Read(mbapBuff, binary.BigEndian, &protocolIdentifier); err != nil {
			log.Debug("读取protocolIdentifier失败")
			return
		}

		if err := binary.Read(mbapBuff, binary.BigEndian, &length); err != nil {
			log.Debug("读取length失败")
			return
		}

		if err := binary.Read(mbapBuff, binary.BigEndian, &slaveId); err != nil {
			log.Debug("读取slaveId失败")
			return
		}

		if transactionId != uint16(msgID){

			return
		}

		if protocolIdentifier != 0{
			return
		}

		if length != uint16(len(registerBuff)-13){
			return
		}


		data := registerBuff[14:(14+length-1)]
		dataBuff := bytes.NewReader(data)

		var functionCode uint8
		var datalen uint8

		if err := binary.Read(dataBuff, binary.BigEndian, &functionCode); err != nil {
			log.Debug("读取functionCode失败")
			return
		}

		if err := binary.Read(dataBuff, binary.BigEndian, &datalen); err != nil {
			log.Debug("读取functionCode失败")
			return
		}

		strReply,err := dbutil.HashGet(utils.GATEWAY_SITE_XINGONG,site_sid)
		if err !=nil{
			log.Infof("设备查询失败或未同步到redis:%v",site_sid)
			return
		}
		siteParams := &SiteParams{}
		err =json.Unmarshal([]byte(strReply), &siteParams)
		if err!=nil{
			log.Infof("json反序列化失败:%v",strReply)
			return
		}

		if siteParams.NumTemp <=120{

			if siteParams.NumTemp == uint16(datalen/2){


				for i:=uint16(0);i< siteParams.NumTemp ;i++{

					var temperatureVal uint16
					if err := binary.Read(dataBuff, binary.BigEndian, &temperatureVal); err != nil {
						log.Debug("读取slaveId失败")
						return
					}

					if temperatureVal == 2010{
						continue
					}

					if temperatureVal !=0{

						ftemperatureVal := float32(temperatureVal)/10.0

						uuid := fmt.Sprintf("%sC3%04d",site_sid,i+1)
						reply,err := dbutil.HashGet(utils.DEVICES_STATUS_HASH,uuid)
						if err !=nil{
							log.Infof("设备查询失败或未同步到redis:%v",uuid)
							continue
						}
						meterLastStatus := MeterStatus{}
						err =json.Unmarshal([]byte(reply), &meterLastStatus)
						if err!=nil{
							log.Infof("json反序列化失败:%v",reply)
							continue
						}

						if meterLastStatus.Status == 2 || meterLastStatus.Status == 0 {
							dbutil.SetDeviceStatus(meterLastStatus.SiteId,uuid,1)
						}

						dateTime := time.Now().Format("2006-01-02 15:04:05")
						meterStatus :=&MeterStatus{
							Status: 1,
							SiteId: meterLastStatus.SiteId,
							Lasttime: dateTime,
							Protocol: meterLastStatus.Protocol,
						}

						meterStatusJson, err := json.Marshal(meterStatus)
						if err != nil {
							log.Errorf("JSON序列化时出现错误, 错误信息：%v", err.Error())
							continue
						}

						err = dbutil.HashSet(utils.DEVICES_STATUS_HASH,uuid,meterStatusJson)
						if err !=nil{
							log.Errorf("redis 存储失败",uuid)
							continue
						}




						err = dbutil.StringSet(utils.DEVICES_VALUE_STRING+":"+uuid+":"+"temperature",ftemperatureVal)
						if err != nil{
							log.Errorf("存储数据失败：%v:%v-%v",uuid,"temperature",ftemperatureVal)
						}
					}

				}
			}


			//下一次询问门磁电压
			if msgID == 2{
				askType := uint32(msgID+3)
				data, _ := utils.ReadHoldingRegisters(1,20160,siteParams.NumDoorMagnetism, askType-1)
				fmt.Printf( "send: %2X ", data)
				conn.SetProperty("askType",int(askType))
				conn.SetTimeOut(time.Second*10)
				conn.SendMsg(uint8(askType),data)
			}

		}else{

		}

	}

}


func (*BatteryVoltageDoorMagnetismApi) Handle (request ziface.IRequest){

	registerBuff := request.GetData()
	msgID :=request.GetMsgID()
	fmt.Printf(string(msgID))
	//dataBuff := bytes.NewReader(registerBuff)
	log.Debugf("%2X ",registerBuff)
	//conn := request.GetConnection()

	byteUuid := registerBuff[0:7]

	var site_sid string
	site_sid= fmt.Sprintf( "%2X", byteUuid)
	fmt.Println(site_sid)

	conn :=  request.GetConnection()
	iSiteSid,err := conn.GetProperty("siteSid")
	if err !=nil{
		log.Infof("conn.GetProperty fail:%v",err)
		return
	}

	siteSid,ok := iSiteSid.(string)

	if !ok{
		log.Infof("IsiteSid fail")
		return
	}

	if site_sid == siteSid{

		mbap := registerBuff[7:14]


		mbapBuff := bytes.NewReader(mbap)

		var transactionId uint16
		var protocolIdentifier uint16
		var length	uint16
		var slaveId uint8


		if err := binary.Read(mbapBuff, binary.BigEndian, &transactionId); err != nil {
			log.Debug("读取transactionId失败")
			return
		}

		if err := binary.Read(mbapBuff, binary.BigEndian, &protocolIdentifier); err != nil {
			log.Debug("读取protocolIdentifier失败")
			return
		}

		if err := binary.Read(mbapBuff, binary.BigEndian, &length); err != nil {
			log.Debug("读取length失败")
			return
		}

		if err := binary.Read(mbapBuff, binary.BigEndian, &slaveId); err != nil {
			log.Debug("读取slaveId失败")
			return
		}

		if transactionId != uint16(msgID){

			return
		}

		if protocolIdentifier != 0{
			return
		}

		if length != uint16(len(registerBuff)-13){
			return
		}

		data := registerBuff[14:(14+length-1)]
		dataBuff := bytes.NewReader(data)

		var functionCode uint8
		var datalen uint8

		if err := binary.Read(dataBuff, binary.BigEndian, &functionCode); err != nil {
			log.Debug("读取functionCode失败")
			return
		}

		if err := binary.Read(dataBuff, binary.BigEndian, &datalen); err != nil {
			log.Debug("读取functionCode失败")
			return
		}

		strReply,err := dbutil.HashGet(utils.GATEWAY_SITE_XINGONG,site_sid)
		if err !=nil{
			log.Infof("设备查询失败或未同步到redis:%v",site_sid)
			return
		}
		siteParams := &SiteParams{}
		err =json.Unmarshal([]byte(strReply), &siteParams)
		if err!=nil{
			log.Infof("json反序列化失败:%v",strReply)
			return
		}

		if siteParams.NumDoorMagnetism > 20 {
			siteParams.NumDoorMagnetism = 20
		}

		if siteParams.NumDoorMagnetism == uint16(datalen/2){


			for i:=uint16(0);i< siteParams.NumDoorMagnetism ;i++{

				var battryVoltage uint16
				if err := binary.Read(dataBuff, binary.BigEndian, &battryVoltage); err != nil {
					log.Debug("读取slaveId失败")
					return
				}

				if battryVoltage !=0{

					fbattryVoltage := float32(battryVoltage)*10.0 //  /100*1000 转换为mv

					uuid := fmt.Sprintf("%sC7%04d",site_sid,i+1)
					reply,err := dbutil.HashGet(utils.DEVICES_STATUS_HASH,uuid)
					if err !=nil{
						log.Infof("设备查询失败或未同步到redis:%v",uuid)
						continue
					}
					meterLastStatus := MeterStatus{}
					err =json.Unmarshal([]byte(reply), &meterLastStatus)
					if err!=nil{
						log.Infof("json反序列化失败:%v",reply)
						continue
					}
					err = dbutil.StringSet(utils.DEVICES_VALUE_STRING+":"+uuid+":"+"battery",fbattryVoltage)
					if err != nil{
						log.Errorf("存储数据失败：%v:%v-%v",uuid,"battery",fbattryVoltage)
					}
				}

			}
		}


		//下一次询问门磁状态
		if msgID == 5{
			askType := int(msgID)
			data, _ := utils.ReadHoldingRegisters(1,10160,siteParams.NumDoorMagnetism, uint32(askType))
			fmt.Printf( "send: %2X ", data)
			conn.SetProperty("askType",askType+1)
			conn.SetTimeOut(time.Second*10)
			conn.SendMsg(uint8(askType+1),data)
		}




	}
}


func (*DoorMagnetismApi) Handle (request ziface.IRequest){

	registerBuff := request.GetData()
	msgID :=request.GetMsgID()
	fmt.Printf(string(msgID))
	//dataBuff := bytes.NewReader(registerBuff)
	log.Debugf("%2X ",registerBuff)
	//conn := request.GetConnection()

	byteUuid := registerBuff[0:7]

	var site_sid string
	site_sid= fmt.Sprintf( "%2X", byteUuid)
	fmt.Println(site_sid)

	conn :=  request.GetConnection()
	iSiteSid,err := conn.GetProperty("siteSid")
	if err !=nil{
		log.Infof("conn.GetProperty fail:%v",err)
		return
	}

	siteSid,ok := iSiteSid.(string)

	if !ok{
		log.Infof("IsiteSid fail")
		return
	}

	if site_sid == siteSid{

		mbap := registerBuff[7:14]


		mbapBuff := bytes.NewReader(mbap)

		var transactionId uint16
		var protocolIdentifier uint16
		var length	uint16
		var slaveId uint8


		if err := binary.Read(mbapBuff, binary.BigEndian, &transactionId); err != nil {
			log.Debug("读取transactionId失败")
			return
		}

		if err := binary.Read(mbapBuff, binary.BigEndian, &protocolIdentifier); err != nil {
			log.Debug("读取protocolIdentifier失败")
			return
		}

		if err := binary.Read(mbapBuff, binary.BigEndian, &length); err != nil {
			log.Debug("读取length失败")
			return
		}

		if err := binary.Read(mbapBuff, binary.BigEndian, &slaveId); err != nil {
			log.Debug("读取slaveId失败")
			return
		}

		if transactionId != uint16(msgID){

			return
		}

		if protocolIdentifier != 0{
			return
		}

		if length != uint16(len(registerBuff)-13){
			return
		}


		data := registerBuff[14:(14+length-1)]
		dataBuff := bytes.NewReader(data)

		var functionCode uint8
		var datalen uint8

		if err := binary.Read(dataBuff, binary.BigEndian, &functionCode); err != nil {
			log.Debug("读取functionCode失败")
			return
		}

		if err := binary.Read(dataBuff, binary.BigEndian, &datalen); err != nil {
			log.Debug("读取functionCode失败")
			return
		}

		strReply,err := dbutil.HashGet(utils.GATEWAY_SITE_XINGONG,site_sid)
		if err !=nil{
			log.Infof("设备查询失败或未同步到redis:%v",site_sid)
			return
		}
		siteParams := &SiteParams{}
		err =json.Unmarshal([]byte(strReply), &siteParams)
		if err!=nil{
			log.Infof("json反序列化失败:%v",strReply)
			return
		}

		if siteParams.NumDoorMagnetism > 20 {
			siteParams.NumDoorMagnetism = 20
		}

		if siteParams.NumDoorMagnetism == uint16(datalen/2){


			for i:=uint16(0);i< siteParams.NumDoorMagnetism ;i++{

				var doorMagnetismStatus uint16
				if err := binary.Read(dataBuff, binary.BigEndian, &doorMagnetismStatus); err != nil {
					log.Debug("读取slaveId失败")
					return
				}

				if doorMagnetismStatus == 2010{
					continue
				}




				uuid := fmt.Sprintf("%sC7%04d",site_sid,i+1)
				reply,err := dbutil.HashGet(utils.DEVICES_STATUS_HASH,uuid)
				if err !=nil{
					log.Infof("设备查询失败或未同步到redis:%v",uuid)
					continue
				}
				meterLastStatus := MeterStatus{}
				err =json.Unmarshal([]byte(reply), &meterLastStatus)
				if err!=nil{
					log.Infof("json反序列化失败:%v",reply)
					continue
				}


				if meterLastStatus.Status == 2 || meterLastStatus.Status == 0 {
					dbutil.SetDeviceStatus(meterLastStatus.SiteId,uuid,1)
				}

				dateTime := time.Now().Format("2006-01-02 15:04:05")
				meterStatus :=&MeterStatus{
					Status: 1,
					SiteId: meterLastStatus.SiteId,
					Lasttime: dateTime,
					Protocol: meterLastStatus.Protocol,
				}

				meterStatusJson, err := json.Marshal(meterStatus)
				if err != nil {
					log.Errorf("JSON序列化时出现错误, 错误信息：%v", err.Error())
					continue
				}

				err = dbutil.HashSet(utils.DEVICES_STATUS_HASH,uuid,meterStatusJson)
				if err !=nil{
					log.Errorf("redis 存储失败",uuid)
					continue
				}



				err = dbutil.StringSet(utils.DEVICES_VALUE_STRING+":"+uuid+":"+"door_magnetism",doorMagnetismStatus)
				if err != nil{
					log.Errorf("存储数据失败：%v:%v-%v",uuid,"door_magnetism",doorMagnetismStatus)
				}

			}
		}


		//下一次询问水浸电池电压
		if msgID == 6{
			askType := uint32(msgID)
			data, _ := utils.ReadHoldingRegisters(1,20140,siteParams.NumWaterImmersion, askType)
			fmt.Printf( "send: %2X ", data)
			conn.SetProperty("askType",int(askType+1))
			conn.SetTimeOut(time.Second*10)
			conn.SendMsg(uint8(askType),data)
		}

	}
}

func (*BatteryVoltageWaterImmersion) Handle (request ziface.IRequest) {


	registerBuff := request.GetData()
	msgID :=request.GetMsgID()
	fmt.Printf(string(msgID))
	//dataBuff := bytes.NewReader(registerBuff)
	log.Debugf("%2X ",registerBuff)
	//conn := request.GetConnection()

	byteUuid := registerBuff[0:7]

	var site_sid string
	site_sid= fmt.Sprintf( "%2X", byteUuid)
	fmt.Println(site_sid)

	conn :=  request.GetConnection()
	iSiteSid,err := conn.GetProperty("siteSid")
	if err !=nil{
		log.Infof("conn.GetProperty fail:%v",err)
		return
	}

	siteSid,ok := iSiteSid.(string)

	if !ok{
		log.Infof("IsiteSid fail")
		return
	}

	if site_sid == siteSid{

		mbap := registerBuff[7:14]


		mbapBuff := bytes.NewReader(mbap)

		var transactionId uint16
		var protocolIdentifier uint16
		var length	uint16
		var slaveId uint8


		if err := binary.Read(mbapBuff, binary.BigEndian, &transactionId); err != nil {
			log.Debug("读取transactionId失败")
			return
		}

		if err := binary.Read(mbapBuff, binary.BigEndian, &protocolIdentifier); err != nil {
			log.Debug("读取protocolIdentifier失败")
			return
		}

		if err := binary.Read(mbapBuff, binary.BigEndian, &length); err != nil {
			log.Debug("读取length失败")
			return
		}

		if err := binary.Read(mbapBuff, binary.BigEndian, &slaveId); err != nil {
			log.Debug("读取slaveId失败")
			return
		}

		if transactionId != uint16(msgID){

			return
		}

		if protocolIdentifier != 0{
			return
		}

		if length != uint16(len(registerBuff)-13){
			return
		}

		data := registerBuff[14:(14+length-1)]
		dataBuff := bytes.NewReader(data)

		var functionCode uint8
		var datalen uint8

		if err := binary.Read(dataBuff, binary.BigEndian, &functionCode); err != nil {
			log.Debug("读取functionCode失败")
			return
		}

		if err := binary.Read(dataBuff, binary.BigEndian, &datalen); err != nil {
			log.Debug("读取functionCode失败")
			return
		}

		strReply,err := dbutil.HashGet(utils.GATEWAY_SITE_XINGONG,site_sid)
		if err !=nil{
			log.Infof("设备查询失败或未同步到redis:%v",site_sid)
			return
		}
		siteParams := &SiteParams{}
		err =json.Unmarshal([]byte(strReply), &siteParams)
		if err!=nil{
			log.Infof("json反序列化失败:%v",strReply)
			return
		}

		if siteParams.NumWaterImmersion > 20 {
			siteParams.NumWaterImmersion = 20
		}

		if siteParams.NumWaterImmersion == uint16(datalen/2){


			for i:=uint16(0);i< siteParams.NumWaterImmersion ;i++{

				var battryVoltage uint16
				if err := binary.Read(dataBuff, binary.BigEndian, &battryVoltage); err != nil {
					log.Debug("读取slaveId失败")
					return
				}

				if battryVoltage !=0{

					fbattryVoltage := float32(battryVoltage)*10.0 //  /100*1000 转换为mv

					uuid := fmt.Sprintf("%sC4%04d",site_sid,i+1)//水浸类型C4
					reply,err := dbutil.HashGet(utils.DEVICES_STATUS_HASH,uuid)
					if err !=nil{
						log.Infof("设备查询失败或未同步到redis:%v",uuid)
						continue
					}
					meterLastStatus := MeterStatus{}
					err =json.Unmarshal([]byte(reply), &meterLastStatus)
					if err!=nil{
						log.Infof("json反序列化失败:%v",reply)
						continue
					}
					err = dbutil.StringSet(utils.DEVICES_VALUE_STRING+":"+uuid+":"+"battery",fbattryVoltage)
					if err != nil{
						log.Errorf("存储数据失败：%v:%v-%v",uuid,"battery",fbattryVoltage)
					}
				}

			}
		}


		//下一次询问水浸状态
		if msgID == 7{
			askType := int(msgID)
			data, _ := utils.ReadHoldingRegisters(1,10140,siteParams.NumWaterImmersion, uint32(askType))
			fmt.Printf( "send: %2X ", data)
			conn.SetProperty("askType",askType+1)
			conn.SetTimeOut(time.Second*10)
			conn.SendMsg(uint8(askType+1),data)
		}

	}

}


func (*WaterImmersion) Handle (request ziface.IRequest){

	registerBuff := request.GetData()
	msgID :=request.GetMsgID()
	fmt.Printf(string(msgID))
	//dataBuff := bytes.NewReader(registerBuff)
	log.Debugf("%2X ",registerBuff)
	//conn := request.GetConnection()

	byteUuid := registerBuff[0:7]

	var site_sid string
	site_sid= fmt.Sprintf( "%2X", byteUuid)
	fmt.Println(site_sid)

	conn :=  request.GetConnection()
	iSiteSid,err := conn.GetProperty("siteSid")
	if err !=nil{
		log.Infof("conn.GetProperty fail:%v",err)
		return
	}

	siteSid,ok := iSiteSid.(string)

	if !ok{
		log.Infof("IsiteSid fail")
		return
	}

	if site_sid == siteSid{

		mbap := registerBuff[7:14]


		mbapBuff := bytes.NewReader(mbap)

		var transactionId uint16
		var protocolIdentifier uint16
		var length	uint16
		var slaveId uint8


		if err := binary.Read(mbapBuff, binary.BigEndian, &transactionId); err != nil {
			log.Debug("读取transactionId失败")
			return
		}

		if err := binary.Read(mbapBuff, binary.BigEndian, &protocolIdentifier); err != nil {
			log.Debug("读取protocolIdentifier失败")
			return
		}

		if err := binary.Read(mbapBuff, binary.BigEndian, &length); err != nil {
			log.Debug("读取length失败")
			return
		}

		if err := binary.Read(mbapBuff, binary.BigEndian, &slaveId); err != nil {
			log.Debug("读取slaveId失败")
			return
		}

		if transactionId != uint16(msgID){

			return
		}

		if protocolIdentifier != 0{
			return
		}

		if length != uint16(len(registerBuff)-13){
			return
		}


		data := registerBuff[14:(14+length-1)]
		dataBuff := bytes.NewReader(data)

		var functionCode uint8
		var datalen uint8

		if err := binary.Read(dataBuff, binary.BigEndian, &functionCode); err != nil {
			log.Debug("读取functionCode失败")
			return
		}

		if err := binary.Read(dataBuff, binary.BigEndian, &datalen); err != nil {
			log.Debug("读取functionCode失败")
			return
		}

		strReply,err := dbutil.HashGet(utils.GATEWAY_SITE_XINGONG,site_sid)
		if err !=nil{
			log.Infof("设备查询失败或未同步到redis:%v",site_sid)
			return
		}
		siteParams := &SiteParams{}
		err =json.Unmarshal([]byte(strReply), &siteParams)
		if err!=nil{
			log.Infof("json反序列化失败:%v",strReply)
			return
		}

		if siteParams.NumWaterImmersion > 20 {
			siteParams.NumWaterImmersion = 20
		}

		if siteParams.NumWaterImmersion == uint16(datalen/2){


			for i:=uint16(0);i< siteParams.NumWaterImmersion ;i++{

				var waterImmersionStatus uint16
				if err := binary.Read(dataBuff, binary.BigEndian, &waterImmersionStatus); err != nil {
					log.Debug("读取slaveId失败")
					return
				}

				if waterImmersionStatus == 2010{
					continue
				}


				uuid := fmt.Sprintf("%sC4%04d",site_sid,i+1)
				reply,err := dbutil.HashGet(utils.DEVICES_STATUS_HASH,uuid)
				if err !=nil{
					log.Infof("设备查询失败或未同步到redis:%v",uuid)
					continue
				}
				meterLastStatus := MeterStatus{}
				err =json.Unmarshal([]byte(reply), &meterLastStatus)
				if err!=nil{
					log.Infof("json反序列化失败:%v",reply)
					continue
				}


				if meterLastStatus.Status == 2 || meterLastStatus.Status == 0 {
					dbutil.SetDeviceStatus(meterLastStatus.SiteId,uuid,1)
				}

				dateTime := time.Now().Format("2006-01-02 15:04:05")
				meterStatus :=&MeterStatus{
					Status: 1,
					SiteId: meterLastStatus.SiteId,
					Lasttime: dateTime,
					Protocol: meterLastStatus.Protocol,
				}

				meterStatusJson, err := json.Marshal(meterStatus)
				if err != nil {
					log.Errorf("JSON序列化时出现错误, 错误信息：%v", err.Error())
					continue
				}

				err = dbutil.HashSet(utils.DEVICES_STATUS_HASH,uuid,meterStatusJson)
				if err !=nil{
					log.Errorf("redis 存储失败",uuid)
					continue
				}


				err = dbutil.StringSet(utils.DEVICES_VALUE_STRING+":"+uuid+":"+"water_immersion",waterImmersionStatus)
				if err != nil{
					log.Errorf("存储数据失败：%v:%v-%v",uuid,"water_immersion",waterImmersionStatus)
				}

			}
		}


		//下一次询问烟感电池电压
		if msgID == 8{
			askType := uint32(msgID)
			data, _ := utils.ReadHoldingRegisters(1,15000,siteParams.NumSmokeSensation, askType)
			fmt.Printf( "send: %2X ", data)
			conn.SetProperty("askType",int(askType+1))
			conn.SetTimeOut(time.Second*10)
			conn.SendMsg(uint8(askType),data)
		}

	}
}


func (*BatteryVoltageSmokeSensation) Handle (request ziface.IRequest) {


	registerBuff := request.GetData()
	msgID :=request.GetMsgID()
	fmt.Printf(string(msgID))
	//dataBuff := bytes.NewReader(registerBuff)
	log.Debugf("%2X ",registerBuff)
	//conn := request.GetConnection()

	byteUuid := registerBuff[0:7]

	var site_sid string
	site_sid= fmt.Sprintf( "%2X", byteUuid)
	fmt.Println(site_sid)

	conn :=  request.GetConnection()
	iSiteSid,err := conn.GetProperty("siteSid")
	if err !=nil{
		log.Infof("conn.GetProperty fail:%v",err)
		return
	}

	siteSid,ok := iSiteSid.(string)

	if !ok{
		log.Infof("IsiteSid fail")
		return
	}

	if site_sid == siteSid{

		mbap := registerBuff[7:14]


		mbapBuff := bytes.NewReader(mbap)

		var transactionId uint16
		var protocolIdentifier uint16
		var length	uint16
		var slaveId uint8


		if err := binary.Read(mbapBuff, binary.BigEndian, &transactionId); err != nil {
			log.Debug("读取transactionId失败")
			return
		}

		if err := binary.Read(mbapBuff, binary.BigEndian, &protocolIdentifier); err != nil {
			log.Debug("读取protocolIdentifier失败")
			return
		}

		if err := binary.Read(mbapBuff, binary.BigEndian, &length); err != nil {
			log.Debug("读取length失败")
			return
		}

		if err := binary.Read(mbapBuff, binary.BigEndian, &slaveId); err != nil {
			log.Debug("读取slaveId失败")
			return
		}

		if transactionId != uint16(msgID){

			return
		}

		if protocolIdentifier != 0{
			return
		}

		if length != uint16(len(registerBuff)-13){
			return
		}

		data := registerBuff[14:(14+length-1)]
		dataBuff := bytes.NewReader(data)

		var functionCode uint8
		var datalen uint8

		if err := binary.Read(dataBuff, binary.BigEndian, &functionCode); err != nil {
			log.Debug("读取functionCode失败")
			return
		}

		if err := binary.Read(dataBuff, binary.BigEndian, &datalen); err != nil {
			log.Debug("读取functionCode失败")
			return
		}

		strReply,err := dbutil.HashGet(utils.GATEWAY_SITE_XINGONG,site_sid)
		if err !=nil{
			log.Infof("设备查询失败或未同步到redis:%v",site_sid)
			return
		}
		siteParams := &SiteParams{}
		err =json.Unmarshal([]byte(strReply), &siteParams)
		if err!=nil{
			log.Infof("json反序列化失败:%v",strReply)
			return
		}

		//烟感最多接入50个
		if siteParams.NumSmokeSensation > 50 {
			siteParams.NumSmokeSensation = 50
		}

		if siteParams.NumSmokeSensation == uint16(datalen/2){


			for i:=uint16(0);i< siteParams.NumSmokeSensation ;i++{

				var batteryVoltage uint16
				if err := binary.Read(dataBuff, binary.BigEndian, &batteryVoltage); err != nil {
					log.Debug("读取slaveId失败")
					return
				}

				if batteryVoltage !=0{

					flatteryVoltage := float32(batteryVoltage) //  烟感的电池电压为百分比

					uuid := fmt.Sprintf("%sC8%04d",site_sid,i+1)//烟感类型C8
					reply,err := dbutil.HashGet(utils.DEVICES_STATUS_HASH,uuid)
					if err !=nil{
						log.Infof("设备查询失败或未同步到redis:%v",uuid)
						continue
					}
					meterLastStatus := MeterStatus{}
					err =json.Unmarshal([]byte(reply), &meterLastStatus)
					if err!=nil{
						log.Infof("json反序列化失败:%v",reply)
						continue
					}
					err = dbutil.StringSet(utils.DEVICES_VALUE_STRING+":"+uuid+":"+"battery_percentage", flatteryVoltage)
					if err != nil{
						log.Errorf("存储数据失败：%v:%v-%v",uuid,"battery", flatteryVoltage)
					}
				}

			}
		}


		//下一次询问烟感状态
		if msgID == 9{
			askType := int(msgID)
			data, _ := utils.ReadHoldingRegisters(1,5000,siteParams.NumSmokeSensation, uint32(askType))
			fmt.Printf( "send: %2X ", data)
			conn.SetProperty("askType",askType+1)
			conn.SetTimeOut(time.Second*10)
			conn.SendMsg(uint8(askType+1),data)
		}

	}

}


func (*SmokeSensation) Handle (request ziface.IRequest){

	registerBuff := request.GetData()
	msgID :=request.GetMsgID()
	fmt.Printf(string(msgID))
	//dataBuff := bytes.NewReader(registerBuff)
	log.Debugf("%2X ",registerBuff)
	//conn := request.GetConnection()

	byteUuid := registerBuff[0:7]

	var site_sid string
	site_sid= fmt.Sprintf( "%2X", byteUuid)
	fmt.Println(site_sid)

	conn :=  request.GetConnection()
	iSiteSid,err := conn.GetProperty("siteSid")
	if err !=nil{
		log.Infof("conn.GetProperty fail:%v",err)
		return
	}

	siteSid,ok := iSiteSid.(string)

	if !ok{
		log.Infof("IsiteSid fail")
		return
	}

	if site_sid == siteSid{

		mbap := registerBuff[7:14]


		mbapBuff := bytes.NewReader(mbap)

		var transactionId uint16
		var protocolIdentifier uint16
		var length	uint16
		var slaveId uint8


		if err := binary.Read(mbapBuff, binary.BigEndian, &transactionId); err != nil {
			log.Debug("读取transactionId失败")
			return
		}

		if err := binary.Read(mbapBuff, binary.BigEndian, &protocolIdentifier); err != nil {
			log.Debug("读取protocolIdentifier失败")
			return
		}

		if err := binary.Read(mbapBuff, binary.BigEndian, &length); err != nil {
			log.Debug("读取length失败")
			return
		}

		if err := binary.Read(mbapBuff, binary.BigEndian, &slaveId); err != nil {
			log.Debug("读取slaveId失败")
			return
		}

		if transactionId != uint16(msgID){

			return
		}

		if protocolIdentifier != 0{
			return
		}

		if length != uint16(len(registerBuff)-13){
			return
		}


		data := registerBuff[14:(14+length-1)]
		dataBuff := bytes.NewReader(data)

		var functionCode uint8
		var datalen uint8

		if err := binary.Read(dataBuff, binary.BigEndian, &functionCode); err != nil {
			log.Debug("读取functionCode失败")
			return
		}

		if err := binary.Read(dataBuff, binary.BigEndian, &datalen); err != nil {
			log.Debug("读取functionCode失败")
			return
		}

		strReply,err := dbutil.HashGet(utils.GATEWAY_SITE_XINGONG,site_sid)
		if err !=nil{
			log.Infof("设备查询失败或未同步到redis:%v",site_sid)
			return
		}
		siteParams := &SiteParams{}
		err =json.Unmarshal([]byte(strReply), &siteParams)
		if err!=nil{
			log.Infof("json反序列化失败:%v",strReply)
			return
		}

		//烟感最多接入50个
		if siteParams.NumSmokeSensation > 50 {
			siteParams.NumSmokeSensation = 50
		}

		if siteParams.NumSmokeSensation == uint16(datalen/2){


			for i:=uint16(0);i< siteParams.NumSmokeSensation ;i++{

				var smokeSensationStatus uint16
				if err := binary.Read(dataBuff, binary.BigEndian, &smokeSensationStatus); err != nil {
					log.Debug("读取slaveId失败")
					return
				}

				if smokeSensationStatus == 2010{
					continue
				}


				uuid := fmt.Sprintf("%sC8%04d",site_sid,i+1)
				reply,err := dbutil.HashGet(utils.DEVICES_STATUS_HASH,uuid)
				if err !=nil{
					log.Infof("设备查询失败或未同步到redis:%v",uuid)
					continue
				}
				meterLastStatus := MeterStatus{}
				err =json.Unmarshal([]byte(reply), &meterLastStatus)
				if err!=nil{
					log.Infof("json反序列化失败:%v",reply)
					continue
				}

				if meterLastStatus.Status == 2 || meterLastStatus.Status == 0 {
					dbutil.SetDeviceStatus(meterLastStatus.SiteId,uuid,1)
				}

				dateTime := time.Now().Format("2006-01-02 15:04:05")
				meterStatus :=&MeterStatus{
					Status: 1,
					SiteId: meterLastStatus.SiteId,
					Lasttime: dateTime,
					Protocol: meterLastStatus.Protocol,
				}

				meterStatusJson, err := json.Marshal(meterStatus)
				if err != nil {
					log.Errorf("JSON序列化时出现错误, 错误信息：%v", err.Error())
					continue
				}

				err = dbutil.HashSet(utils.DEVICES_STATUS_HASH,uuid,meterStatusJson)
				if err !=nil{
					log.Errorf("redis 存储失败",uuid)
					continue
				}






				err = dbutil.StringSet(utils.DEVICES_VALUE_STRING+":"+uuid+":"+"alert",smokeSensationStatus)
				if err != nil{
					log.Errorf("存储数据失败：%v:%v-%v",uuid,"alert",smokeSensationStatus)
				}

			}
		}


		//下一次询问水位电池电压
		if msgID == 10{
			askType := uint32(msgID)
			data, _ := utils.ReadHoldingRegisters(1,20180,siteParams.NumWaterLevel, askType)
			fmt.Printf( "send: %2X ", data)
			conn.SetProperty("askType",int(askType+1))
			conn.SetTimeOut(time.Second*10)
			conn.SendMsg(uint8(askType),data)
		}

	}
}


func (*BatteryVoltageWaterLevel) Handle (request ziface.IRequest) {


	registerBuff := request.GetData()
	msgID :=request.GetMsgID()
	fmt.Printf(string(msgID))
	//dataBuff := bytes.NewReader(registerBuff)
	log.Debugf("%2X ",registerBuff)
	//conn := request.GetConnection()

	byteUuid := registerBuff[0:7]

	var site_sid string
	site_sid= fmt.Sprintf( "%2X", byteUuid)
	fmt.Println(site_sid)

	conn :=  request.GetConnection()
	iSiteSid,err := conn.GetProperty("siteSid")
	if err !=nil{
		log.Infof("conn.GetProperty fail:%v",err)
		return
	}

	siteSid,ok := iSiteSid.(string)

	if !ok{
		log.Infof("IsiteSid fail")
		return
	}

	if site_sid == siteSid{

		mbap := registerBuff[7:14]


		mbapBuff := bytes.NewReader(mbap)

		var transactionId uint16
		var protocolIdentifier uint16
		var length	uint16
		var slaveId uint8


		if err := binary.Read(mbapBuff, binary.BigEndian, &transactionId); err != nil {
			log.Debug("读取transactionId失败")
			return
		}

		if err := binary.Read(mbapBuff, binary.BigEndian, &protocolIdentifier); err != nil {
			log.Debug("读取protocolIdentifier失败")
			return
		}

		if err := binary.Read(mbapBuff, binary.BigEndian, &length); err != nil {
			log.Debug("读取length失败")
			return
		}

		if err := binary.Read(mbapBuff, binary.BigEndian, &slaveId); err != nil {
			log.Debug("读取slaveId失败")
			return
		}

		if transactionId != uint16(msgID){

			return
		}

		if protocolIdentifier != 0{
			return
		}

		if length != uint16(len(registerBuff)-13){
			return
		}

		data := registerBuff[14:(14+length-1)]
		dataBuff := bytes.NewReader(data)

		var functionCode uint8
		var datalen uint8

		if err := binary.Read(dataBuff, binary.BigEndian, &functionCode); err != nil {
			log.Debug("读取functionCode失败")
			return
		}

		if err := binary.Read(dataBuff, binary.BigEndian, &datalen); err != nil {
			log.Debug("读取functionCode失败")
			return
		}

		strReply,err := dbutil.HashGet(utils.GATEWAY_SITE_XINGONG,site_sid)
		if err !=nil{
			log.Infof("设备查询失败或未同步到redis:%v",site_sid)
			return
		}
		siteParams := &SiteParams{}
		err =json.Unmarshal([]byte(strReply), &siteParams)
		if err!=nil{
			log.Infof("json反序列化失败:%v",strReply)
			return
		}

		//信工集中器最多装20个水位
		if siteParams.NumWaterLevel > 20 {
			siteParams.NumWaterLevel = 20
		}

		if siteParams.NumWaterLevel == uint16(datalen/2){


			for i:=uint16(0);i< siteParams.NumWaterLevel ;i++{

				var batteryVoltage uint16
				if err := binary.Read(dataBuff, binary.BigEndian, &batteryVoltage); err != nil {
					log.Debug("读取slaveId失败")
					return
				}

				if batteryVoltage !=0{

					flatteryVoltage := float32(batteryVoltage)*10.0 //  /100*1000 转换为mv

					uuid := fmt.Sprintf("%sC5%04d",site_sid,i+1)//水位类型C5
					reply,err := dbutil.HashGet(utils.DEVICES_STATUS_HASH,uuid)
					if err !=nil{
						log.Infof("设备查询失败或未同步到redis:%v",uuid)
						continue
					}
					meterLastStatus := MeterStatus{}
					err =json.Unmarshal([]byte(reply), &meterLastStatus)
					if err!=nil{
						log.Infof("json反序列化失败:%v",reply)
						continue
					}
					err = dbutil.StringSet(utils.DEVICES_VALUE_STRING+":"+uuid+":"+"battery", flatteryVoltage)
					if err != nil{
						log.Errorf("存储数据失败：%v:%v-%v",uuid,"battery", flatteryVoltage)
					}
				}

			}
		}


		//下一次询问水位数据
		if msgID == 11{
			askType := int(msgID)
			data, _ := utils.ReadHoldingRegisters(1,10180,siteParams.NumWaterLevel, uint32(askType))
			fmt.Printf( "send: %2X ", data)
			conn.SetProperty("askType",askType+1)
			conn.SetTimeOut(time.Second*10)
			conn.SendMsg(uint8(askType+1),data)
		}

	}

}


func (*WaterLevel) Handle (request ziface.IRequest){

	registerBuff := request.GetData()
	msgID :=request.GetMsgID()
	fmt.Printf(string(msgID))
	//dataBuff := bytes.NewReader(registerBuff)
	log.Debugf("%2X ",registerBuff)
	//conn := request.GetConnection()

	byteUuid := registerBuff[0:7]

	var site_sid string
	site_sid= fmt.Sprintf( "%2X", byteUuid)
	fmt.Println(site_sid)

	conn :=  request.GetConnection()
	iSiteSid,err := conn.GetProperty("siteSid")
	if err !=nil{
		log.Infof("conn.GetProperty fail:%v",err)
		return
	}

	siteSid,ok := iSiteSid.(string)

	if !ok{
		log.Infof("IsiteSid fail")
		return
	}

	if site_sid == siteSid{

		mbap := registerBuff[7:14]


		mbapBuff := bytes.NewReader(mbap)

		var transactionId uint16
		var protocolIdentifier uint16
		var length	uint16
		var slaveId uint8


		if err := binary.Read(mbapBuff, binary.BigEndian, &transactionId); err != nil {
			log.Debug("读取transactionId失败")
			return
		}

		if err := binary.Read(mbapBuff, binary.BigEndian, &protocolIdentifier); err != nil {
			log.Debug("读取protocolIdentifier失败")
			return
		}

		if err := binary.Read(mbapBuff, binary.BigEndian, &length); err != nil {
			log.Debug("读取length失败")
			return
		}

		if err := binary.Read(mbapBuff, binary.BigEndian, &slaveId); err != nil {
			log.Debug("读取slaveId失败")
			return
		}

		if transactionId != uint16(msgID){

			return
		}

		if protocolIdentifier != 0{
			return
		}

		if length != uint16(len(registerBuff)-13){
			return
		}


		data := registerBuff[14:(14+length-1)]
		dataBuff := bytes.NewReader(data)

		var functionCode uint8
		var datalen uint8

		if err := binary.Read(dataBuff, binary.BigEndian, &functionCode); err != nil {
			log.Debug("读取functionCode失败")
			return
		}

		if err := binary.Read(dataBuff, binary.BigEndian, &datalen); err != nil {
			log.Debug("读取functionCode失败")
			return
		}

		strReply,err := dbutil.HashGet(utils.GATEWAY_SITE_XINGONG,site_sid)
		if err !=nil{
			log.Infof("设备查询失败或未同步到redis:%v",site_sid)
			return
		}
		siteParams := &SiteParams{}
		err =json.Unmarshal([]byte(strReply), &siteParams)
		if err!=nil{
			log.Infof("json反序列化失败:%v",strReply)
			return
		}

		if siteParams.NumWaterLevel > 20 {
			siteParams.NumWaterLevel = 20
		}

		if siteParams.NumWaterLevel == uint16(datalen/2){


			for i:=uint16(0);i< siteParams.NumWaterLevel ;i++{

				var waterLevel uint16
				if err := binary.Read(dataBuff, binary.BigEndian, &waterLevel); err != nil {
					log.Debug("读取slaveId失败")
					return
				}

				if waterLevel == 2010{
					continue
				}


				uuid := fmt.Sprintf("%sC5%04d",site_sid,i+1)//水位类型是C5
				reply,err := dbutil.HashGet(utils.DEVICES_STATUS_HASH,uuid)
				if err !=nil{
					log.Infof("设备查询失败或未同步到redis:%v",uuid)
					continue
				}
				meterLastStatus := MeterStatus{}
				err =json.Unmarshal([]byte(reply), &meterLastStatus)
				if err!=nil{
					log.Infof("json反序列化失败:%v",reply)
					continue
				}



				if meterLastStatus.Status == 2 || meterLastStatus.Status == 0 {
					dbutil.SetDeviceStatus(meterLastStatus.SiteId,uuid,1)
				}

				dateTime := time.Now().Format("2006-01-02 15:04:05")
				meterStatus :=&MeterStatus{
					Status: 1,
					SiteId: meterLastStatus.SiteId,
					Lasttime: dateTime,
					Protocol: meterLastStatus.Protocol,
				}

				meterStatusJson, err := json.Marshal(meterStatus)
				if err != nil {
					log.Errorf("JSON序列化时出现错误, 错误信息：%v", err.Error())
					continue
				}

				err = dbutil.HashSet(utils.DEVICES_STATUS_HASH,uuid,meterStatusJson)
				if err !=nil{
					log.Errorf("redis 存储失败",uuid)
					continue
				}



				err = dbutil.StringSet(utils.DEVICES_VALUE_STRING+":"+uuid+":"+"water_level",waterLevel)
				if err != nil{
					log.Errorf("存储数据失败：%v:%v-%v",uuid,"water_level",waterLevel)
				}

			}
		}


		//下一次询问温湿度电池电压
		if msgID == 12{
			askType := uint32(msgID)
			data, _ := utils.ReadHoldingRegisters(1,20100,siteParams.NumTempAndHum*2, askType)
			fmt.Printf( "send: %2X ", data)
			conn.SetProperty("askType",int(askType+1))
			conn.SetTimeOut(time.Second*10)
			conn.SendMsg(uint8(askType),data)
		}

	}
}


func (*BatteryVoltageTempAndHum) Handle (request ziface.IRequest) {


	registerBuff := request.GetData()
	msgID :=request.GetMsgID()
	fmt.Printf(string(msgID))
	//dataBuff := bytes.NewReader(registerBuff)
	log.Debugf("%2X ",registerBuff)
	//conn := request.GetConnection()

	byteUuid := registerBuff[0:7]

	var site_sid string
	site_sid= fmt.Sprintf( "%2X", byteUuid)
	fmt.Println(site_sid)

	conn :=  request.GetConnection()
	iSiteSid,err := conn.GetProperty("siteSid")
	if err !=nil{
		log.Infof("conn.GetProperty fail:%v",err)
		return
	}

	siteSid,ok := iSiteSid.(string)

	if !ok{
		log.Infof("IsiteSid fail")
		return
	}

	if site_sid == siteSid{

		mbap := registerBuff[7:14]


		mbapBuff := bytes.NewReader(mbap)

		var transactionId uint16
		var protocolIdentifier uint16
		var length	uint16
		var slaveId uint8


		if err := binary.Read(mbapBuff, binary.BigEndian, &transactionId); err != nil {
			log.Debug("读取transactionId失败")
			return
		}

		if err := binary.Read(mbapBuff, binary.BigEndian, &protocolIdentifier); err != nil {
			log.Debug("读取protocolIdentifier失败")
			return
		}

		if err := binary.Read(mbapBuff, binary.BigEndian, &length); err != nil {
			log.Debug("读取length失败")
			return
		}

		if err := binary.Read(mbapBuff, binary.BigEndian, &slaveId); err != nil {
			log.Debug("读取slaveId失败")
			return
		}

		if transactionId != uint16(msgID){

			return
		}

		if protocolIdentifier != 0{
			return
		}

		if length != uint16(len(registerBuff)-13){
			return
		}

		data := registerBuff[14:(14+length-1)]
		dataBuff := bytes.NewReader(data)

		var functionCode uint8
		var datalen uint8

		if err := binary.Read(dataBuff, binary.BigEndian, &functionCode); err != nil {
			log.Debug("读取functionCode失败")
			return
		}

		if err := binary.Read(dataBuff, binary.BigEndian, &datalen); err != nil {
			log.Debug("读取functionCode失败")
			return
		}

		strReply,err := dbutil.HashGet(utils.GATEWAY_SITE_XINGONG,site_sid)
		if err !=nil{
			log.Infof("设备查询失败或未同步到redis:%v",site_sid)
			return
		}

		siteParams := &SiteParams{}
		err =json.Unmarshal([]byte(strReply), &siteParams)
		if err!=nil{
			log.Infof("json反序列化失败:%v",strReply)
			return
		}

		//信工集中器最多装20个温湿度
		if siteParams.NumTempAndHum > 20 {
			siteParams.NumTempAndHum = 20
		}

		if siteParams.NumTempAndHum == uint16(datalen/4){


			for i:=uint16(0);i< siteParams.NumTempAndHum ;i++{

				//温湿度传感器两个电池数据
				var batteryVoltage1 uint16
				if err := binary.Read(dataBuff, binary.BigEndian, &batteryVoltage1); err != nil {
					log.Debug("读取slaveId失败")
					return
				}

				var batteryVoltage2 uint16
				if err := binary.Read(dataBuff, binary.BigEndian, &batteryVoltage2); err != nil {
					log.Debug("读取slaveId失败")
					return
				}

				if batteryVoltage1 !=0 && batteryVoltage1 == batteryVoltage2{

					flatteryVoltage := float32(batteryVoltage1)*10.0 //  /100*1000 转换为mv

					uuid := fmt.Sprintf("%sC6%04d",site_sid,i+1)//水位类型C5
					reply,err := dbutil.HashGet(utils.DEVICES_STATUS_HASH,uuid)
					if err !=nil{
						log.Infof("设备查询失败或未同步到redis:%v",uuid)
						continue
					}
					meterLastStatus := MeterStatus{}
					err =json.Unmarshal([]byte(reply), &meterLastStatus)
					if err!=nil{
						log.Infof("json反序列化失败:%v",reply)
						continue
					}
					err = dbutil.StringSet(utils.DEVICES_VALUE_STRING+":"+uuid+":"+"battery", flatteryVoltage)
					if err != nil{
						log.Errorf("存储数据失败：%v:%v-%v",uuid,"battery", flatteryVoltage)
					}
				}

			}
		}


		//下一次询问温湿度数据
		if msgID == 13{
			askType := int(msgID)
			data, _ := utils.ReadHoldingRegisters(1,10100,siteParams.NumTempAndHum*2, uint32(askType))
			fmt.Printf( "send: %2X ", data)
			conn.SetProperty("askType",askType+1)
			conn.SetTimeOut(time.Second*10)
			conn.SendMsg(uint8(askType+1),data)
		}

	}

}


func (*TempAndHum) Handle (request ziface.IRequest){

	registerBuff := request.GetData()
	msgID :=request.GetMsgID()
	fmt.Printf(string(msgID))
	//dataBuff := bytes.NewReader(registerBuff)
	log.Debugf("%2X ",registerBuff)
	//conn := request.GetConnection()

	byteUuid := registerBuff[0:7]

	var site_sid string
	site_sid= fmt.Sprintf( "%2X", byteUuid)
	fmt.Println(site_sid)

	conn :=  request.GetConnection()
	iSiteSid,err := conn.GetProperty("siteSid")
	if err !=nil{
		log.Infof("conn.GetProperty fail:%v",err)
		return
	}

	siteSid,ok := iSiteSid.(string)

	if !ok{
		log.Infof("IsiteSid fail")
		return
	}

	if site_sid == siteSid{

		mbap := registerBuff[7:14]


		mbapBuff := bytes.NewReader(mbap)

		var transactionId uint16
		var protocolIdentifier uint16
		var length	uint16
		var slaveId uint8


		if err := binary.Read(mbapBuff, binary.BigEndian, &transactionId); err != nil {
			log.Debug("读取transactionId失败")
			return
		}

		if err := binary.Read(mbapBuff, binary.BigEndian, &protocolIdentifier); err != nil {
			log.Debug("读取protocolIdentifier失败")
			return
		}

		if err := binary.Read(mbapBuff, binary.BigEndian, &length); err != nil {
			log.Debug("读取length失败")
			return
		}

		if err := binary.Read(mbapBuff, binary.BigEndian, &slaveId); err != nil {
			log.Debug("读取slaveId失败")
			return
		}

		if transactionId != uint16(msgID){

			return
		}

		if protocolIdentifier != 0{
			return
		}

		if length != uint16(len(registerBuff)-13){
			return
		}


		data := registerBuff[14:(14+length-1)]
		dataBuff := bytes.NewReader(data)

		var functionCode uint8
		var datalen uint8

		if err := binary.Read(dataBuff, binary.BigEndian, &functionCode); err != nil {
			log.Debug("读取functionCode失败")
			return
		}

		if err := binary.Read(dataBuff, binary.BigEndian, &datalen); err != nil {
			log.Debug("读取functionCode失败")
			return
		}

		strReply,err := dbutil.HashGet(utils.GATEWAY_SITE_XINGONG,site_sid)
		if err !=nil{
			log.Infof("设备查询失败或未同步到redis:%v",site_sid)
			return
		}
		siteParams := &SiteParams{}
		err =json.Unmarshal([]byte(strReply), &siteParams)
		if err!=nil{
			log.Infof("json反序列化失败:%v",strReply)
			return
		}

		if siteParams.NumTempAndHum > 20 {
			siteParams.NumTempAndHum = 20
		}

		if siteParams.NumTempAndHum == uint16(datalen/4){


			for i:=uint16(0);i< siteParams.NumTempAndHum ;i++{

				var temperatureVal uint16
				if err := binary.Read(dataBuff, binary.BigEndian, &temperatureVal); err != nil {
					log.Debug("读取slaveId失败")
					return
				}

				if temperatureVal == 2010{
					continue
				}


				if temperatureVal !=0{

					ftemperatureVal := float32(temperatureVal)/10.0

					uuid := fmt.Sprintf("%sC6%04d",site_sid,i+1)//水位类型是C5
					reply,err := dbutil.HashGet(utils.DEVICES_STATUS_HASH,uuid)
					if err !=nil{
						log.Infof("设备查询失败或未同步到redis:%v",uuid)
						continue
					}
					meterLastStatus := MeterStatus{}
					err =json.Unmarshal([]byte(reply), &meterLastStatus)
					if err!=nil{
						log.Infof("json反序列化失败:%v",reply)
						continue
					}
					err = dbutil.StringSet(utils.DEVICES_VALUE_STRING+":"+uuid+":"+"temperature",ftemperatureVal)
					if err != nil{
						log.Errorf("存储数据失败：%v:%v-%v",uuid,"temperature",ftemperatureVal)
					}

				}


				var humidityVal uint16
				if err := binary.Read(dataBuff, binary.BigEndian, &humidityVal); err != nil {
					log.Debug("读取slaveId失败")
					return
				}

				if humidityVal == 2010{
					continue
				}

				if humidityVal !=0{

					fhumidityVal := float32(humidityVal)/10.0

					uuid := fmt.Sprintf("%sC6%04d",site_sid,i+1)//温湿度类型是C6
					reply,err := dbutil.HashGet(utils.DEVICES_STATUS_HASH,uuid)
					if err !=nil{
						log.Infof("设备查询失败或未同步到redis:%v",uuid)
						continue
					}
					meterLastStatus := MeterStatus{}
					err =json.Unmarshal([]byte(reply), &meterLastStatus)
					if err!=nil{
						log.Infof("json反序列化失败:%v",reply)
						continue
					}


					if meterLastStatus.Status == 2 || meterLastStatus.Status == 0 {
						dbutil.SetDeviceStatus(meterLastStatus.SiteId,uuid,1)
					}

					dateTime := time.Now().Format("2006-01-02 15:04:05")
					meterStatus :=&MeterStatus{
						Status: 1,
						SiteId: meterLastStatus.SiteId,
						Lasttime: dateTime,
						Protocol: meterLastStatus.Protocol,
					}

					meterStatusJson, err := json.Marshal(meterStatus)
					if err != nil {
						log.Errorf("JSON序列化时出现错误, 错误信息：%v", err.Error())
						continue
					}

					err = dbutil.HashSet(utils.DEVICES_STATUS_HASH,uuid,meterStatusJson)
					if err !=nil{
						log.Errorf("redis 存储失败",uuid)
						continue
					}


					err = dbutil.StringSet(utils.DEVICES_VALUE_STRING+":"+uuid+":"+"humidity",fhumidityVal)
					if err != nil{
						log.Errorf("存储数据失败：%v:%v-%v",uuid,"humidity",fhumidityVal)
					}

				}

			}
		}


		//等待下次心跳然后再轮询
		if msgID == 14{
			askType := uint32(msgID)
			//data, _ := utils.ReadHoldingRegisters(1,20100,siteParams.NumTempAndHum, askType)
			//fmt.Printf( "send: %2X ", data)
			conn.SetProperty("askType",int(0))
			conn.SetTimeOut(time.Second*10)
			conn.SendMsg(uint8(askType),data)
		}

	}
}

